<template>
  <div>
    <div
      v-if="is_show_waiting"
      class="pass_change_finish"
    >请稍后...</div>
    <div v-else>
      <div class="register_con">
        <div class="l_con fl">
          <a class="reg_logo"><img src="/static/images/logo.png"></a>
          <div class="reg_slogan">商品美 · 种类多 · 欢迎光临</div>
          <div class="reg_banner"></div>
        </div>

        <div class="r_con fr">
          <div class="reg_title clearfix">
            <h1>绑定用户</h1>
          </div>
          <div
            class="reg_form clearfix"
            id="app"
            v-cloak
          >
            <form id="reg_form">
              <ul>
                <li>
                  <label>手机号:</label>
                  <input
                    type="text"
                    v-model="mobile"
                    v-on:blur="check_phone"
                    name="phone"
                    id="phone"
                  >
                  <span
                    v-show="error_phone"
                    class="error_tip"
                  >{{ error_phone_message }}</span>
                </li>
                <li>
                  <label>密码:</label>
                  <input
                    type="password"
                    v-model="password"
                    v-on:blur="check_pwd"
                    name="pwd"
                    id="pwd"
                  >
                  <span
                    v-show="error_password"
                    class="error_tip"
                  >密码最少8位，最长20位</span>
                </li>
                <li>
                  <label>图片验证码:</label>
                  <input
                    type="text"
                    v-model="image_code"
                    @blur="check_image_code"
                    style="width:172px; height: 40px;"
                  >
                  <img
                    :src="image_url"
                    @click="generate_image_code"
                    style="margin-left: 3px;width: 108px;height: 40px;"
                  />
                  <span
                    v-show="error_image_code"
                    class="error_tip"
                  >请输入图形验证码</span>
                </li>
                <li>
                  <label>短信验证码:</label>
                  <input
                    type="text"
                    v-model="sms_code"
                    @blur="check_sms_code"
                    class="msg_input"
                  >
                  <a
                    @click="send_sms_code"
                    class="get_msg_code"
                  >{{ sms_code_tip }}</a>
                  <span
                    v-show="error_sms_code"
                    class="error_tip"
                  >{{ error_sms_code_message }}</span>
                </li>
                <li class="reg_sub">
                  <input
                    @click="on_submit"
                    type="button"
                    value="保 存"
                    name=""
                  >
                </li>
              </ul>
            </form>
          </div>
        </div>
      </div>

      <div class="footer no-mp">
        <div class="foot_link">
          <a href="#">关于我们</a>
          <span>|</span>
          <a href="#">联系我们</a>
          <span>|</span>
          <a href="#">招聘人才</a>
          <span>|</span>
          <a href="#">友情链接</a>
        </div>
        <p>CopyRight © 2016 北京美多商业股份有限公司 All Rights Reserved</p>
        <p>电话：010-****888 京ICP备*******8号</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      host: host,
      is_show_waiting: true,

      error_password: false,
      error_phone: false,
      error_sms_code: false,
      error_phone_message: '',
      error_sms_code_message: '',
      error_image_code: false,

      sms_code_tip: '获取短信验证码',
      sending_flag: false, // 正在发送短信标志

      password: '',
      mobile: '',
      sms_code: '',
      access_token: '',

      image_url: '',  // 图片地址
      image_code: '',
    }
  },
  created() {
    debugger
    this.generate_image_code()
    // 从路径中获取微博回调给前端的code
    var code = this.get_query_string('code');
    this.axios.post(this.host + '/weibo/callback/?code=' + code, {
      responseType: 'json',
    }).then(response => {
      debugger
      if (response.data.id) {
        alert(response.data.msg)
        // 用户已绑定
        sessionStorage.clear();
        localStorage.clear();
        localStorage.user_id = response.data.id;
        localStorage.username = response.data.username;
        localStorage.token = response.data.token;
        // var state = this.get_query_string('state');
        location.href = '/';

      }
      if (response.data.type == '0') {
        // 用户未绑定
        this.weibo_uid = response.data.weibo_uid;
        this.is_show_waiting = false;  // 去掉请稍等... 展示 绑定界面
      }
      if (response.data.code == 999) {
        alert(response.data.msg)
      }
    }).catch(error => {
      console.log(error.response.data);
      alert('服务器异常');
    })
  },
  methods: {
    generate_image_code() {
      // debugger
      this.uuid = this.generate_uuid()
      this.image_url = this.host + '/image_codes/' + this.uuid + '/'
      // this.image_url = 'http://localhost:8080/static/images/logo.png'
    },
    check_image_code() {
      var len = this.image_code.length;
      if (len != 4) {
        this.error_image_code = true;
      } else {
        this.error_image_code = false;
      }
    },
    // 获取url路径参数    
    get_query_string(name) {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
      var r = window.location.search.substr(1).match(reg);
      if (r != null) {
        return decodeURI(r[2]);
      }
      return null;
    },
    // 生成uuid
    generate_uuid() {
      var d = new Date().getTime();
      if (window.performance && typeof window.performance.now === "function") {
        d += performance.now(); //use high-precision timer if available
      }
      var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
      });
      return uuid;
    },
    check_pwd() {
      var len = this.password.length;
      if (len < 8 || len > 20) {
        this.error_password = true;
      } else {
        this.error_password = false;
      }
    },
    check_phone() {
      var re = /^1[345789]\d{9}$/;
      if (re.test(this.mobile)) {
        this.error_phone = false;
      } else {
        this.error_phone_message = '您输入的手机号格式不正确';
        this.error_phone = true;
      }
    },
    check_sms_code() {
      if (!this.sms_code) {
        this.error_sms_code_message = '请填写短信验证码';
        this.error_sms_code = true;
      } else {
        this.error_sms_code = false;
      }
    },
    // 发送手机短信验证码
    send_sms_code() {
      if (this.sending_flag == true) {
        return;
      }
      this.sending_flag = true;

      // 校验参数，保证输入框有数据填写
      this.check_phone();

      if (this.error_phone == true) {
        this.sending_flag = false;
        return;
      }

      // 向后端接口发送请求，让后端发送短信验证码
      this.axios.get(this.host + '/sms_codes/' + this.mobile + '/' + '?image_code=' + this.image_code + '&uuid=' + this.uuid, {
        responseType: 'json'
      })
        .then(response => {
          // 表示后端发送短信成功
          // 倒计时60秒，60秒后允许用户再次点击发送短信验证码的按钮
          var num = 60;
          // 设置一个计时器
          var t = setInterval(() => {
            if (num == 1
            ) {
              // 如果计时器到最后, 清除计时器对象
              clearInterval(t);
              // 将点击获取验证码的按钮展示的文本回复成原始文本
              this.sms_code_tip = '获取短信验证码';
              // 将点击按钮的onclick事件函数恢复回去
              this.sending_flag = false;
            }
            else {
              num -= 1;
              // 展示倒计时信息
              this.sms_code_tip = num + '秒';
            }
          }, 1000)
        }).catch(error => {
          console.log(error.response.data);
          this.sending_flag = false;
        })
    },
    // 保存
    on_submit() {
      debugger
      this.check_pwd();
      this.check_phone();
      this.check_sms_code();

      if (this.error_password == false &&
        this.error_phone == false &&
        this.error_sms_code == false) {
        this.axios.post(this.host + '/weibo/binduser/', {
          password: this.password,
          mobile: this.mobile,
          sms_code: this.sms_code,
          weibo_uid: this.weibo_uid
        }, {
          responseType: 'json',
        }).then(response => {
          debugger
          if (response.data.code == '0') {
            // 记录用户登录状态
            localStorage.clear();
            localStorage.token = response.data.token;
            localStorage.user_id = response.data.id;
            localStorage.username = response.data.username;
            location.href = '/'
          } else {
            alert(response.data.msg)
          }

        })
        // .catch(error => {
        //   debugger
        //   if (error.response.status == 400
        //   ) {
        //     this.error_sms_code_message = error.response.data.message;
        //     this.error_sms_code = true;
        //   }
        //   else {
        //     console.log(error.response.data);
        //   }
        // })
      }
    }
  }
}
</script>

<style>
</style>